<?php

class Export extends CI_Model {

	function __construct() {
		parent::__construct();
		// Load the required models
		
	}

	/**
	 * Converts an array into a csv file.
	 * @param arr $data Array for data to export
	 * @param arr $headers Headers of the CSV file
	 */
	public function create_csv($data, $headers) {
		$attachment = true;

		// Create a random filename
		$filename = _file_name();

		if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $fp = fopen('php://output', 'w');
        } else {
            $fp = fopen($filename, 'w');
        }
        
        if($headers) {
            // output header row (if at least one row exists)
            $row = mysql_fetch_assoc($result);
            if($row) {
                fputcsv($fp, array_keys($row));
                // reset pointer back to beginning
                mysql_data_seek($result, 0);
            }
        }
        
        while($row = mysql_fetch_assoc($result)) {
            fputcsv($fp, $row);
        }
        
        fclose($fp);
    }

    // Using the function
    $sql = "SELECT * FROM table";
    // $db_conn should be a valid db handle

    // output as an attachment
    query_to_csv($db_conn, $sql, "test.csv", true);

    // output to file system
    query_to_csv($db_conn, $sql, "test.csv", false);

	}

	private function _file_name() {
		$length = 10;
		$alfa = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
		$token = "";
		for($i = 0; $i < $length; $i ++) {
			$token .= $alfa[rand(0, strlen($alfa) - 1)];
		}    
		return $token;
	}

}